package com.itheima.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itheima.domain.User;
import com.itheima.service.UserService;


/**
 * 自定义Realm
 * @author hj
 *
 */
@Component
public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;


	/**
	 * 执行授权逻辑
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		System.out.println("执行授权逻辑");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//获取当前用户的id
		
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		User dbUser = userService.findById(user.getId());
		info.addStringPermission(dbUser.getPerms());
		return info;
	}

	/**
	 * 执行认证逻辑
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		// TODO Auto-generated method stub
		System.out.println("执行认证逻辑");
		//执行Shiro判断逻辑
		//假设数据库的用户名和密码就是"eric" "123456"
		//判断用户名
		UsernamePasswordToken  tokens = (UsernamePasswordToken) arg0;
		User user = userService.findByName(tokens.getUsername());
		if(user==null) {
			//用户名不存在
			return null;//shiro底层会抛出unkonwCountException;
		}	
		
		return new SimpleAuthenticationInfo(user, user.getPassword(), "");
	}

}
